package cn.edu.sdjzu.xg23.kcsj01_backend.service.impl;



import cn.edu.sdjzu.xg23.kcsj01_backend.entity.*;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.AbsAchievementMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.EmployeeAssStandardMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.StandardMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.FileService;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.StandardService;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.SupportingMaterialService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.SnowflakeIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@EnableTransactionManagement
public class StandardServiceImpl implements StandardService {

    @Autowired
    private StandardMapper standardMapper;
    @Autowired
    private AbsAchievementMapper absAchievementMapper;
    @Autowired
    private SnowflakeIdGenerator idGenerator;
    @Autowired
    private EmployeeAssStandardMapper employeeAssStandardMapper;

    @Autowired
    private FileService fileService;

    @Autowired

    private SupportingMaterialService supportingMaterialService;
    @Override
    @Transactional // 声明事务
    public boolean save(Standard standard) {
        Long sharedId = idGenerator.generateId();

        // 1. 插入 Achievement 相关记录
        absAchievementMapper.addAchievement(sharedId, "标准");

        // 2. 插入 standard 记录
        standard.setId(sharedId);
        boolean success = standardMapper.save(standard);
        boolean insertSuccess = false;
        boolean insertFilesSuccess = false;
        if (success && standard.getApplicants() != null && !standard.getApplicants().isEmpty()) {
            for (EmployeeAssStandard applicant : standard.getApplicants()) {
                applicant.setStandard(new Standard(sharedId));
            }

            insertSuccess = employeeAssStandardMapper.save(standard.getApplicants());
        }

        if (insertSuccess && standard.getSupportingMaterial() != null && !standard.getSupportingMaterial().isEmpty()) {
            for (SupportingMaterial supportingMaterial : standard.getSupportingMaterial()) {
                supportingMaterial.setAchievement(new Standard(sharedId));// 添加Achievement关联
            }
            insertFilesSuccess = supportingMaterialService.addSupportingMaterials(sharedId, standard.getSupportingMaterial());
        }


        return success && insertSuccess && insertFilesSuccess;
//        return success;

    }
    // 通过删除Achievement表数据 级联删除专利和对应支撑材料
    @Override
    @Transactional
    public boolean delete(Long standardId) {
        try {
            // 1. 查询该专利的所有支撑材料
            List<SupportingMaterial> materials = supportingMaterialService.findByAchievementId(standardId);

            // 2. 提取文件URL并删除物理文件
            if (!materials.isEmpty()) {
                List<String> fileUrls = materials.stream()
                        .map(SupportingMaterial::getFileUrl)
                        .collect(Collectors.toList());

                Map<String, Object> deleteResult = fileService.deleteFiles(fileUrls);
                // 可以在这里处理删除失败的情况，目前暂时忽略继续执行
            }

            // 3. 删除数据库记录（级联删除支撑材料）
            return absAchievementMapper.deleteById(standardId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean update(Standard standard) {
        // 1. 更新专利基本信息
        boolean updateSuccess = standardMapper.update(standard);

        if (updateSuccess) {
            Long standardId = standard.getId();

            // 2. 处理申报人信息
            if (standard.getApplicants() != null) {
                // 删除该专利原有的所有申报人关系
                employeeAssStandardMapper.delete(standardId);

                // 重新插入新的申报人关系
                for (EmployeeAssStandard applicant : standard.getApplicants()) {
                    applicant.setStandard(new Standard(standardId));
                }
                boolean applicantSuccess = employeeAssStandardMapper.save(standard.getApplicants());
                if (!applicantSuccess) {
                    return false;
                }
            }

            // 3. 处理支撑材料
            if (standard.getSupportingMaterial() != null) {
                // 查询现有的支撑材料
                List<SupportingMaterial> existingMaterials = supportingMaterialService.findByAchievementId(standardId);

                // 找出需要删除的文件（现有但不在新提交列表中的）
                List<SupportingMaterial> materialsToDelete = existingMaterials.stream()
                        .filter(existing -> standard.getSupportingMaterial().stream()
                                .noneMatch(newMat -> newMat.getFileUrl().equals(existing.getFileUrl())))
                        .collect(Collectors.toList());

                // 找出需要保留的文件（现有且在新提交列表中的）
                List<SupportingMaterial> materialsToKeep = existingMaterials.stream()
                        .filter(existing -> standard.getSupportingMaterial().stream()
                                .anyMatch(newMat -> newMat.getFileUrl().equals(existing.getFileUrl())))
                        .collect(Collectors.toList());

                // 找出需要新增的文件（新提交但不在现有列表中的）
                List<SupportingMaterial> materialsToAdd = standard.getSupportingMaterial().stream()
                        .filter(newMat -> existingMaterials.stream()
                                .noneMatch(existing -> existing.getFileUrl().equals(newMat.getFileUrl())))
                        .collect(Collectors.toList());

                // 删除需要删除的文件
                if (!materialsToDelete.isEmpty()) {
                    // 删除物理文件
                    List<String> fileUrlsToDelete = materialsToDelete.stream()
                            .map(SupportingMaterial::getFileUrl)
                            .collect(Collectors.toList());
                    fileService.deleteFiles(fileUrlsToDelete);

                    // 删除数据库记录
                    supportingMaterialService.deleteSupportingMaterialsByIds(
                            materialsToDelete.stream()
                                    .map(SupportingMaterial::getId)
                                    .collect(Collectors.toList())
                    );
                }

                // 处理需要新增的文件
                if (!materialsToAdd.isEmpty()) {
                    // 为新文件生成ID
                    for (SupportingMaterial material : materialsToAdd) {
                        material.setId(idGenerator.generateId());
                        material.setAchievement(new Standard(standardId));
                    }

                    // 只添加新文件
                    boolean addSuccess = supportingMaterialService.addSupportingMaterials(standardId, materialsToAdd);
                    if (!addSuccess) {
                        return false;
                    }
                }

                // 保留的文件不需要处理
            }
        }

        return updateSuccess;
    }



    @Override
    public PageInfo<Standard> get(Integer pageNum, Integer pageSize, Standard standard,Long employeeId) {
        PageHelper.startPage(pageNum, pageSize);
        List<Standard> standardList = standardMapper.get(standard,employeeId);
        return new PageInfo<>(standardList);
    }




    @Override
    public boolean approve(Standard standard) {
        return standardMapper.approve(standard);
    }
}